#include "ring_buff.h"
#include "string.h"
#include "stdlib.h"
void ringBuff_init(ringBuffPort_t *Port)
{
	Port->head_index = Port->tail_index = Port->length = 0;	
}

uint8_t ringBuff_noEmpty(ringBuffPort_t *Port)
{
	return Port->length != 0;
}

uint8_t ringBuff_noFull(ringBuffPort_t *Port)
{
	return Port->length < RINGPAGESIZE;
}

uint8_t ringBuff_enqueue(ringBuffPort_t *Port,void *Data,uint8_t Size)
{
	ringBuffPage_t *page;
	if(ringBuff_noFull(Port) == 0)
	{
		return 0;
	}
	
	page = (ringBuffPage_t *)malloc(sizeof(ringBuffPage_t));
	if(page == 0)
	{
		return 0;
	}
	
	page->buff = (void *)malloc(Size);
	if(page->buff == 0)
	{
		free(page);
		return 0;
	}
	
	page->size = Size;
	memcpy(page->buff,Data,Size);
	Port->pages[Port->head_index] = page;
	Port->head_index = (Port->head_index + 1) % RINGBUFFSIZE;
	Port->length++;
	
	return 1;
	

}

uint8_t ringBuff_dequeue(ringBuffPort_t *Port,void *Data,uint8_t *Size)
{
	ringBuffPage_t *page;
	if(ringBuff_noEmpty(Port) == 0)
	{
		return 0;
	}
	
	page = Port->pages[Port->tail_index];
	memcpy(Data,page->buff,page->size);
	*Size = page->size;
	Port->tail_index = (Port->tail_index + 1) % RINGBUFFSIZE;
	Port->length--;
	
	free(page->buff);
	free(page);

	return 1;
	

}
